package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);//获取时间集合

        //存放营业额
        List<Double>turnoverList =new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据、营业额是指:状态为“已完成”的订单金额合计
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN);//最小时间
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);//最大时间

            //创建一个map集合，将条件存入
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            log.info("map集合的数据为：{}",map);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        log.info("返回的两个数据集合为：{}，{}",turnoverList,dateList);
        return TurnoverReportVO
                .builder()
                .turnoverList(StringUtils.join(turnoverList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);//获取时间集合

        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN);//最小时间
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);//最大时间

            //创建一个map集合，将条件存入
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            totalUserList.add(userMapper.getTotalUser(map));
            newUserList.add(userMapper.getnewUser(map));
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);//获取时间集合

        //创建返回类型集合
        List<String> orderCountList = new ArrayList<>();
        List<String> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime =LocalDateTime.of(date, LocalTime.MIN);//最小时间
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);//最大时间

            //创建一个map集合，将条件存入
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            log.info("未添加订单状态条件的map为：{}",map);
            //获取每日订单数
            orderCountList.add(orderMapper.getOrderCount(map));//未添加订单状态条件
            map.put("status", Orders.COMPLETED);//已经完成的订单数量
            log.info("添加订单状态条件的map为：{}",map);
            validOrderCountList.add(orderMapper.getOrderCount(map));//添加订单状态条件
        }

        LocalDateTime beginTime =LocalDateTime.of(begin, LocalTime.MIN);//最小时间
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);//最大时间
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        Integer totalOrderCount = Integer.valueOf(orderMapper.getOrderCount(map));
        map.put("status", Orders.COMPLETED);//已经完成的订单数量
        Integer validOrderCount = Integer.valueOf(orderMapper.getOrderCount(map));;
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排行top10统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);//获取时间集合

        LocalDateTime beginTime =LocalDateTime.of(begin, LocalTime.MIN);//最小时间
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);//最大时间
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status", Orders.COMPLETED);//已经完成的订单数量

        List<GoodsSalesDTO> top10 = orderMapper.getTop10(map);
        List<String> names = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    /**
     * 导出数据报表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //查询数据库，获取营业数据--查询最近30天数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime =LocalDateTime.of(dateBegin, LocalTime.MIN);//最小时间
        LocalDateTime endTime = LocalDateTime.of(dateEnd,LocalTime.MAX);//最大时间

        BusinessDataVO businessDataVO = extracted(beginTime,endTime);

        //通过POI将数据写入到表格文件
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(stream);
            //填充数据--概览数据
            XSSFSheet sheet1 = excel.getSheet("Sheet1");//获取数据页
            //填充时间
            sheet1.getRow(1).getCell(1).setCellValue("时间" + dateBegin + "至" + dateEnd);

            //获取第四行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第五行
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice() );

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = extracted(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));

                //获得某一行
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //通过输出流将表格文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    private BusinessDataVO extracted(LocalDateTime beginTime,LocalDateTime endTime) {

        //新增用户
        Integer newUsers = userMapper.getByTodayCount(beginTime,endTime);
        newUsers = newUsers == null ? 0 : newUsers;
        log.info("新增用户：{}",newUsers);

        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        Integer totalOrderCount = Integer.valueOf(orderMapper.getOrderCount(map));
        log.info("订单完成率，{}",totalOrderCount);
        map.put("status", Orders.COMPLETED);//已经完成的订单数量
        //有效单数
        Integer validOrderCount = Integer.valueOf(orderMapper.getOrderCount(map));
        ;
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        }
        log.info("有效订单数，{}",orderCompletionRate);
        //营业额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null ? 0.0 : turnover;
        log.info("营业额，{}",turnover);
        //平均客单价
        Double unitPrice = 0.0;
        if(validOrderCount != 0) {
            unitPrice = turnover / validOrderCount;
            unitPrice = unitPrice == null ? 0.0 : unitPrice;
        }
        log.info("平均客单价，{}",unitPrice);
        //概览数据
        return BusinessDataVO
                .builder()
                .newUsers(newUsers)
                .unitPrice(unitPrice)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .build();
    }


    private List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        //创建一个时间集合，来存放时间参数
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
            log.info("日期为集合为：{}",dateList);
        }
        return dateList;
    }

}
